#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：tools 
@File ：注册码验证器.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/11/27 上午9:49 
"""

from cryptography.fernet import Fernet
import json
from datetime import datetime

# 注册码存储文件
LICENSE_FILE = "encrypted_licenses.txt"


# 加载加密的注册码
def load_encrypted_licenses():
	try:
		with open(LICENSE_FILE, "rb") as file:
			encrypted_licenses = file.read()
		# 解密注册码
		cipher_suite = Fernet(Fernet.generate_key())  # 这里需要使用与生成注册码时相同的密钥
		decrypted_licenses = cipher_suite.decrypt(encrypted_licenses).decode()
		# 将JSON字符串转换回字典
		licenses = json.loads(decrypted_licenses)
		return licenses
	except FileNotFoundError:
		return {}


# 验证注册码
def validate_license_code(license_code, licenses):
	if license_code in licenses:
		expiration_date = datetime.fromisoformat(licenses[license_code])
		if datetime.now() < expiration_date:
			return True
	return False


# 主函数，验证注册码
def main():
	licenses = load_encrypted_licenses()
	user_input_code = input("Please enter your license code: ")
	is_valid = validate_license_code(user_input_code, licenses)
	if is_valid:
		print("License valid.")
	else:
		print("License invalid or expired.")


if __name__ == "__main__":
	main()
